package com.qf.qfusermanager.service;

import com.qf.common.bean.R;
import com.qf.common.dto.CmdParamDto;
import com.qf.common.feigns.MqttApi;
import com.qf.common.feigns.UserApi;
import com.qf.common.model.QfMenu;
import com.qf.common.model.QfUser;
import com.qf.qfusermanager.adapter.UserAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private UserApi userApi;

    @Autowired
    private MqttApi mqttApi;


    public R send(CmdParamDto cmdParamDto) {
        return mqttApi.send(cmdParamDto);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //通过username查询用户信息-通过feign调用 qf-center-service
        QfUser qfUser = userApi.findByUsername(username);

        if (qfUser != null){
            //比较密码
            Collection<? extends GrantedAuthority> auths = AuthorityUtils.createAuthorityList("default");
            UserAdapter userAdapter = new UserAdapter(username,qfUser.getPassword(),auths,qfUser);

            return userAdapter;
        }

        //用户名不存在
        return null;
    }
}
